package com.ruoyi.demo.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.demo.service.JyDemoService;
import com.ruoyi.rsikManage.domain.JyDemoJsonStr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import javax.servlet.ServletContext;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class JyServiceDemoImpl implements JyDemoService {
    @Value("${jy.ip}")
    private String JY_IP;
    @Value("${jy.switch}")
    private boolean JY_SWITCH;

    @Value("${jy.client_id}")
    private String client_id;

    @Value("${jy.client_secret}")
    private String client_secret;


    @Autowired
    private ServletContext servletContext;

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    //请求参数
    String grant_type = "client_credentials";
    String format = "json";
    //对象头中的请求参数
    String user = "usercode:YGSJ";
    String cookie = "usercode=YGSJ";
    String contentType = "application/json";


//    @Autowired
//    private VideoRtspMapper videoRtspMapper;

    /**
     * 设置请求头参数
     */
    public void setHeaders(HttpHeaders headers) {
        //从容器中获取 access_token
        headers.set("Authorization",(String) servletContext.getAttribute("access_token"));
        headers.set("User", user);
        headers.set("Cookie", cookie);
        headers.set("Content-Type", contentType);
    }


    @Override
    public String getPasswordFreeLoginURL() {
        String url = "http://"+JY_IP+":11125/sso/v1/tickets";
        /**
         * 步骤一 获取TGT（登录票据：有效期8小时）
         */
        // 设置请求头信息
        setHeaders(headers);
        // 构造请求体（参数）
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();

        body.add("username", "YGSJ");
        body.add("password", "04FA4605FC5A707EBFFACC824486ED95");
        // 构造请求对象
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, headers);
        // 发送POST请求并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        // 获取响应体中的TGT
        String tgt = response.getBody();
        /*
        步骤二  获取ST（服务票据：有效期一分钟）
         */
        // 构造请求体（参数）
        MultiValueMap<String, String> body2 = new LinkedMultiValueMap<>();
        body2.add("service", "http://"+JY_IP+":9000/cas/validate");
        // 构造请求对象
        HttpEntity<MultiValueMap<String, String>> httpEntity2 = new HttpEntity<>(body2, headers);
        // 发送POST请求并获取响应
        ResponseEntity<String> response2 = restTemplate.postForEntity(url+"/"+tgt, httpEntity2, String.class);
        // 获取响应体中的TGT
        String st = response2.getBody();
        String passwordFreeLoginUrl = "http://"+JY_IP+":9000/cas/validate" + "?ticket=" + st;
        return passwordFreeLoginUrl;
    }

    @Override
    public String getAccessToken() {
        if (!JY_SWITCH) {
            return "{}";
        }
        String url = "http://"+JY_IP+":11125/sso/oauth2.0/accessToken?grant_type=" + grant_type + "&client_id=" + client_id+ "&client_secret=" + client_secret+ "&format=" + format;
        //发送get请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getBody();
    }

    @Override
    public String getNewAccessToken() {
        if (!JY_SWITCH) {
            return "{}";
        }
        //从容器中获取 refresh_token
        String refresh_token = servletContext.getAttribute("refresh_token").toString();
        String url = "http://"+JY_IP+":11125/sso/oauth2.0/accessToken?grant_type="+ grant_type+ "&client_id=" + client_id+ "&client_secret=" + client_secret +"&format=" + format + "&refresh_token=" + refresh_token;
        //发送get请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getBody();
    }

    @Override
    public String eventSubscriptions(Map param) {
        //设置请求头
        setHeaders(headers);
        //构造请求体（参数）
        Map<String, Object> body = new HashMap<>();
        body.put("mode", param.get("mode"));
        body.put("event_type_list", param.get("event_type_list"));
        body.put("accept_url", param.get("accept_url"));
        //构造请求对象
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(body, headers);
        String url = "http://"+JY_IP+":11125/api/eco/v2/evc/event/subscriptions";
        //发送POST请求
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        return response.getBody();
    }

    @Override
    public String selectEventSubscriptions() {

        //设置请求头
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/eco/v2/evc/event/subscriptions";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String deleteEventSubscriptions(Map param) {

        //设置请求头
        setHeaders(headers);
        // 构造请求体（参数）
        Map<String, Object> body = new HashMap<>();
        body.put("event_type_list", param.get("event_type_list"));
        // 构造请求对象
        HttpEntity httpEntity = new HttpEntity(body, headers);
        String url = "http://"+JY_IP+":11125/api/eco/v2/evc/event/subscriptions";

        //发送delete请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String picAddrTrans(List<String> addrList) {
        //设置请求头
        setHeaders(headers);
        // 构造请求对象
        HttpEntity httpEntity = new HttpEntity(addrList, headers);
        String url = "http://"+JY_IP+":11125/api/viid/v3/mda/addr-trans";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String getChannelListWithDevice() {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.channelListWithDevice;
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/bss/v1/udm/channel/list-with-device?page_size=9999";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

//    @Override
//    public List<Map<String,Object>> getLiveStreamUrl(Map param) {
//        // 设置请求头信息
//        setHeaders(headers);
//        // 构造请求对象
//        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
//        param.put("visit_ip","");
////
//        Map<String,Object> result= new HashMap<>();
//        List<Map<String,Object>> mapsRtsp = new ArrayList<>();
//        List<Map> monitorPoints =  videoRtspMapper.selectAllRtsp();
////        String apeIdValue =;
//
//        Object apeIdObj = param.get("apeId");
//        if (apeIdObj != null && !apeIdObj.toString().isEmpty()) {
//            String apeId = apeIdObj.toString();
//            List<Map> filteredList = monitorPoints.stream()
//                    .filter(map -> map.get("apeId").toString().equals(apeId))
//                    .collect(Collectors.toList());
//            monitorPoints = filteredList;
//        }
//
//
////        List<MonitorPoint> mapsApeId = monitorPoints;
////        List<String> mapsRtsp = new ArrayList<>();
////        List<String> apeIdList = mapsApeId.stream()
////                .map(map -> (String) map.get("apeId"))
////                .collect(Collectors.toList());
//        for (Map apeId : monitorPoints) {
//            Map<String,Object> resultMap= new HashMap<>();
//            try {
//                String channel_code = apeId.get("apeId").toString();
////                channel_code="10000000001311000002";
//
////                String stream_type = param.get("stream_type").toString();
//
//                String stream_type = "0";
//
////                String stream_mode = param.get("stream_mode").toString();
//
//                String stream_mode = "3";
//
////                String strea_m_type = param.get("strea m_type").toString();
//
////                String stream_type = "0";
//
//
//
////                String keep_alive = param.get("keep_alive").toString();
//
//                String keep_alive = "100";
//
////                String visit_ip = param.get("visit_ip").toString();
//
//                String visit_ip =JY_LOCALHOST_IP;
//
//
//
//                String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/live/stream/url?channel_code="
//                        + channel_code + "&stream_type=" + stream_type + "&stream_mode=" + stream_mode
//                        +  "&keep_alive=" + keep_alive + "&visit_ip=" + visit_ip;
//                // 发送get请求
//                ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
//                String body = exchange.getBody();
//
//                ObjectMapper objectMapper = new ObjectMapper();
//                Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
//
////              Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");
////              String rtspValue = (String) dataMap.get("rtsp");
//                String rtspValue =  responseMap.get("data").toString();
////                Field[] fields = apeId.getClass().getDeclaredFields();
////                for (Field field : fields) {
////                    field.setAccessible(true);
////                    String fieldName = field.getName();
////                    Object fieldValue = field.get(apeId);
////                    resultMap.put(fieldName, fieldValue.toString());
////                }
//                resultMap.put("rtsp",rtspValue);
//                resultMap.put("rtspUrl",rtspValue+"&visit_ip="+JY_LOCALHOST_IP);
////              resultMap.put("apeData",apeId);
//                resultMap.put("apeId",apeId.get("apeId").toString());
//                resultMap.put("name",apeId.get("name").toString());
//                resultMap.put("ownerApsIp",apeId.get("ownerApsIp").toString());
////
////                result.put("data",resultMap);
//                mapsRtsp.add(resultMap);
////
//                // 其他处理逻辑...
//
//            } catch (Exception e) {
//                // 处理异常，可以进行日志记录等操作
//                e.printStackTrace();
////                resultMap.put("apeData",apeId);
//                resultMap.put("apeId",apeId.get("apeId").toString());
//                resultMap.put("name",apeId.get("name").toString());
//
//                resultMap.put("rtsp","");
////                result.put("data",resultMap);
//                mapsRtsp.add(resultMap);
//
//                // 继续下一次循环
//                continue;
//            }
//        }
//        //
//
//        return mapsRtsp;
//    }


//    @Override
//    public List<Map<String,Object>> getLiveStreamUrlApp(Map param) {
//        // 设置请求头信息
//        setHeaders(headers);
//        // 构造请求对象
//        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
//        String visit_ip = (param.get("visitIp") == null || param.get("visitIp").toString().isEmpty()) ? JY_LOCALHOST_IP : param.get("visitIp").toString();
//
////
//        Map<String,Object> result= new HashMap<>();
//        List<Map<String,Object>> mapsRtsp = new ArrayList<>();
//        List<Map> monitorPoints =  videoRtspMapper.selectAllRtsp();
////        String apeIdValue =;
//
//        Object apeIdObj = param.get("apeId");
//        if (apeIdObj != null && !apeIdObj.toString().isEmpty()) {
//            String apeId = apeIdObj.toString();
//            List<Map> filteredList = monitorPoints.stream()
//                    .filter(map -> map.get("apeId").toString().equals(apeId))
//                    .collect(Collectors.toList());
//            monitorPoints = filteredList;
//        }
//
//
////        List<MonitorPoint> mapsApeId = monitorPoints;
////        List<String> mapsRtsp = new ArrayList<>();
////        List<String> apeIdList = mapsApeId.stream()
////                .map(map -> (String) map.get("apeId"))
////                .collect(Collectors.toList());
//        for (Map apeId : monitorPoints) {
//            Map<String,Object> resultMap= new HashMap<>();
//            try {
//                String channel_code = apeId.get("apeId").toString();
////                channel_code="10000000001311000002";
//
////                String stream_type = param.get("stream_type").toString();
//
//                String stream_type = "0";
//
////                String stream_mode = param.get("stream_mode").toString();
//
//                String stream_mode = "3";
//
////                String strea_m_type = param.get("strea m_type").toString();
//
////                String stream_type = "0";
//
//
//
////                String keep_alive = param.get("keep_alive").toString();
//
//                String keep_alive = "100";
//
////                String visit_ip = param.get("visit_ip").toString();
//
////                String visit_ip =JY_LOCALHOST_IP;
//
//
//
//                String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/live/stream/url?channel_code="
//                        + channel_code + "&stream_type=" + stream_type + "&stream_mode=" + stream_mode
//                        +  "&keep_alive=" + keep_alive + "&visit_ip=" + visit_ip;
//                // 发送get请求
//                ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
//                String body = exchange.getBody();
//
//                ObjectMapper objectMapper = new ObjectMapper();
//                Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
//
////              Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");
////              String rtspValue = (String) dataMap.get("rtsp");
//                String rtspValue =  responseMap.get("data").toString();
////                Field[] fields = apeId.getClass().getDeclaredFields();
////                for (Field field : fields) {
////                    field.setAccessible(true);
////                    String fieldName = field.getName();
////                    Object fieldValue = field.get(apeId);
////                    resultMap.put(fieldName, fieldValue.toString());
////                }
//                resultMap.put("rtsp",rtspValue);
//                resultMap.put("rtspUrl",rtspValue);
////              resultMap.put("apeData",apeId);
//                resultMap.put("apeId",apeId.get("apeId").toString());
//                resultMap.put("name",apeId.get("name").toString());
//                resultMap.put("ownerApsIp",apeId.get("ownerApsIp").toString());
////
////                result.put("data",resultMap);
//                mapsRtsp.add(resultMap);
////
//                // 其他处理逻辑...
//
//            } catch (Exception e) {
//                // 处理异常，可以进行日志记录等操作
//                e.printStackTrace();
////                resultMap.put("apeData",apeId);
//                resultMap.put("apeId",apeId.get("apeId").toString());
//                resultMap.put("name",apeId.get("name").toString());
//
//                resultMap.put("rtsp","");
////                result.put("data",resultMap);
//                mapsRtsp.add(resultMap);
//
//                // 继续下一次循环
//                continue;
//            }
//        }
//        //
//
//        return mapsRtsp;
//    }

    public String getLiveStreamUrlOfTheMonitor(String channel_code, String stream_type,String stream_mode, String keep_alive, String visit_ip) throws JsonProcessingException {
        // 设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/live/stream/url?channel_code="
                + channel_code + "&stream_type=" + stream_type + "&stream_mode=" + stream_mode
                +  "&keep_alive=" + keep_alive + "&visit_ip=" + visit_ip;
        // 发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);

        String body = exchange.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
        String rtspValue =  responseMap.get("data").toString();

        return rtspValue;
    }

    @Override
    public String getReplayStreamUrlOfTheMonitor(String channelCode, String startTime, String endTime, String streamMode) {
        // 设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析字符串时间为 LocalDateTime 对象
        LocalDateTime localStartDateTime = LocalDateTime.parse(startTime, formatter);
        LocalDateTime localEndDateTime = LocalDateTime.parse(endTime, formatter);
        ZoneId shanghaiZone = ZoneId.of("GMT+8");
        ZonedDateTime shanghaiStartDateTime = localStartDateTime.atZone(shanghaiZone);
        ZonedDateTime shanghaiEndDateTime = localEndDateTime.atZone(shanghaiZone);

        long startTimestamp = shanghaiStartDateTime.toInstant().getEpochSecond();
        long endTimestamp = shanghaiEndDateTime.toInstant().getEpochSecond();

        int start_time = (int) startTimestamp;
        int end_time = (int) endTimestamp;

        String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                + channelCode + "&start_time=" + start_time + "&end_time="+ end_time +"&stream_mode=" + streamMode
                + "&source_type=0";
        String resStr;
        //发送get请求
        try {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(4000);
            requestFactory.setReadTimeout(5000);
            restTemplate.setRequestFactory(requestFactory);
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            resStr = exchange.getBody();
        } catch (RestClientException e) {
            resStr = e.getMessage();
            throw new RuntimeException(e);
        }
//        JSONObject replayStreamUrlJsonObj = JSONObject.parseObject(exchange.getBody()).getJSONObject("data");
//            resStr = replayStreamUrlJsonObj.getString("url");
        return resStr;
    }


//    @Override
//    public List<Map<String,Object>> getLiveStreamUrlReplay(Map param) {
//
//        // 设置请求头信息
//        setHeaders(headers);
//        // 构造请求对象
//        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
//        param.put("visit_ip","");
////
//        Map<String,Object> result= new HashMap<>();
//        List<Map<String,Object>> mapsRtsp = new ArrayList<>();
//        List<Map> monitorPoints =  videoRtspMapper.selectAllRtsp();
////        String apeIdValue =;
//
////        String startDate = "2023-09-04 12:03:59";
////        String endDate = "2023-09-04 14:03:59";
//
//        // 定义日期时间格式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
//        // 解析字符串时间为 LocalDateTime 对象
//        LocalDateTime localStartDateTime = LocalDateTime.parse(param.get("startTime").toString(), formatter);
//
//        LocalDateTime updatedDateTime10bf = localStartDateTime.plusSeconds(Long.parseLong(PLAY_MINS));
//        System.out.println(localStartDateTime);
//        System.out.println(updatedDateTime10bf);
//
//        LocalDateTime localEndDateTime = LocalDateTime.parse(param.get("endTime").toString(), formatter);
//
//
//        LocalDateTime updatedDateTime10af = localEndDateTime.minusSeconds(Long.parseLong(PLAY_MINS));
//
//        ZoneId shanghaiZone = ZoneId.of("GMT+8");
//        ZonedDateTime shanghaiStartDateTime = updatedDateTime10bf.atZone(shanghaiZone);
//        ZonedDateTime shanghaiEndDateTime = updatedDateTime10af.atZone(shanghaiZone);
//
//        long startTimestamp = shanghaiStartDateTime.toInstant().getEpochSecond();
//        long endTimestamp = shanghaiEndDateTime.toInstant().getEpochSecond();
//
//        int start_time = (int) startTimestamp;
//        int end_time = (int) endTimestamp;
//        // 转换为 UTC 时间戳（秒）
//        int start_time2 = (int)localStartDateTime.toEpochSecond(ZoneOffset.UTC);
//        int end_time2 = (int)localEndDateTime.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(start_time);
//        System.out.println(end_time);
//        System.out.println(start_time2);
//        System.out.println(end_time2);
//        Object apeIdObj = param.get("apeId");
//        if (apeIdObj != null && !apeIdObj.toString().isEmpty()) {
//            String apeId = apeIdObj.toString();
//            List<Map> filteredList = monitorPoints.stream()
//                    .filter(map -> map.get("apeId").toString().equals(apeId))
//                    .collect(Collectors.toList());
//            monitorPoints = filteredList;
//        }
//
//        for (Map apeId : monitorPoints) {
//            Map<String,Object> resultMap= new HashMap<>();
//            try {
//                String channel_code = apeId.get("apeId").toString();
//
////                String stream_mode = param.get("stream_mode").toString();
//
//                String stream_mode = "3";
//
//                String visit_ip =JY_LOCALHOST_IP ;
//
//                String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
//                        + channel_code +  "&start_time="+start_time+"&end_time="+end_time+"&stream_mode=" + stream_mode
//                        + "&source_type=1"+"&visit_ip="+visit_ip;
//                // 发送get请求
//                ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
//                String body = exchange.getBody();
//
//                ObjectMapper objectMapper = new ObjectMapper();
//                Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
//
//
//                String rtspValue =  responseMap.get("data").toString();
//
//                Map<String, String> map = Arrays.stream(rtspValue.replace("{", "").replace("}", "").split(", "))
//                        .map(s -> s.split("="))
//                        .collect(Collectors.toMap(s -> s[0], s -> s[1]));
//
//                resultMap.put("rtsp",map.get("url"));
//                resultMap.put("replayId",map.get("replay_id"));
//                resultMap.put("rtspUrl",map.get("url"));
//                resultMap.put("apeId",apeId.get("apeId").toString());
//                resultMap.put("name",apeId.get("name").toString());
//                resultMap.put("ownerApsIp",apeId.get("ownerApsIp").toString());
////
////                result.put("data",resultMap);
//                mapsRtsp.add(resultMap);
////
//                // 其他处理逻辑...
//
//            } catch (Exception e) {
//                // 处理异常，可以进行日志记录等操作
//                e.printStackTrace();
////                resultMap.put("apeData",apeId);
//                resultMap.put("apeId",apeId.get("apeId").toString());
//                resultMap.put("name",apeId.get("name").toString());
//
//                resultMap.put("rtsp","");
////                result.put("data",resultMap);
//                mapsRtsp.add(resultMap);
//
//                // 继续下一次循环
//                continue;
//            }
//        }
//        //
//
//        return mapsRtsp;
//    }

    @Override
    public String getPlayRecordUrl(String channel_code, String event_time, String event_id) {
        return "http://"+JY_IP+":40087/api/vms/v2/oss-digest-vod/play-record?channel_code=" + channel_code + "&event_time=" + event_time + "&event_id=" + event_id;
    }

    @Override
    public String getIndexAndName() {
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/bss/v1/uuv/users/privilege/device-org/tree";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String addDVR(Map param) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders(headers);
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/bss/v1/udm/video";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String getVideoDiagnosisResults(String channel_name, String start_time,  Integer page_num, Integer page_size) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.videoAnalysisResult;
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/result/record/source";
        //发送get请求
        HashMap<String, Object> map = new HashMap<>();
        map.put("channel_name", channel_name);
        map.put("start_time", start_time);
        map.put("page_num", page_num);
        map.put("page_size", page_size);
        String params = "?channel_name={channel_name}&page_num={page_num}&page_size={page_size}&start_time={start_time}";
        ResponseEntity<String> exchange = restTemplate.exchange(url + params, HttpMethod.GET, httpEntity, String.class, map);
        return exchange.getBody();
    }

    @Override
    public String getVideoDiagnosisResults2( String start_time, String end_time, Integer page_num, Integer page_size) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.videoAnalysisResult;
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/result/record/source";
        //发送get请求
        HashMap<String, Object> map = new HashMap<>();
//        map.put("channel_name", channel_name);
        map.put("start_time", start_time);
        map.put("end_time", start_time);
        map.put("page_num", page_num);
        map.put("page_size", page_size);
//        String params = "?channel_name={channel_name}&page_num={page_num}&page_size={page_size}&start_time={start_time}&end_time={end_time}";
        String params = "?page_num={page_num}&page_size={page_size}&start_time={start_time}&end_time={end_time}";
        ResponseEntity<String> exchange = restTemplate.exchange(url + params, HttpMethod.GET, httpEntity, String.class, map);
        return exchange.getBody();
    }

    @Override
    public String getLastVideoDiagnosisResult(Map param) {
        System.out.println("JY_SWITCH" + JY_SWITCH);
        if (!JY_SWITCH) {
            System.out.println("极云不可以用");
            System.out.println("极云开关没生效!!!!!!!!!!!!!!!!!!!!");
            return JyDemoJsonStr.lastVideoDiagnosisResult;

        }

        System.out.println("极云开关生效!!!!!!!!!!!!!!!!!!!!");


        System.out.println("极云可以用");

        //设置请求头信息
        setHeaders(headers);
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/result/record/last";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
//        return lastVideoDiagnosisResultStr;
    }

    @Override
    public String addVideoDiagnosisScheme(Map param) {
        //设置请求头信息
        setHeaders(headers);
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/scheme";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String updateVideoDiagnosisScheme(String schemeId, Map param) {
        //设置请求头信息
        setHeaders(headers);
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/scheme/{schemeId}";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class, schemeId);
        return exchange.getBody();
    }

    @Override
    public String selectVideoDiagnosisSchemeList(String name, Integer page_num, Integer page_size) {
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        StringBuilder url = new StringBuilder("http://" + JY_IP + ":11125/api/vms/v2/oms/diagnosis/video/scheme?");
        if (name != null) {
            url.append("name=" + name + "&");
        }
        if (page_num != null) {
            url.append("page_num=" + page_num + "&");
        }
        if (page_size != null) {
            url.append("page_size=" + page_size + "&");
        }

        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url.toString(), HttpMethod.GET, httpEntity, String.class);

        return exchange.getBody();
    }

    @Override
    public String selectVideoDiagnosisScheme(String schemeId) {
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/scheme/{schemeId}";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, schemeId);
        return exchange.getBody();
    }

    @Override
    public String deleteVideoDiagnosisSchemes(String schemeIds) {
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/scheme?ids=" + schemeIds;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String addVideoDiagnosisPlan(Map param) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders(headers);
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String updateVideoDiagnosisPlan(String planId, Map param) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders(headers);
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan/{planId}";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class, planId);
        return exchange.getBody();
    }

    @Override
    public String selectVideoDiagnosisPlanList(String name, Integer page_num, Integer page_size) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        StringBuilder url = new StringBuilder("http://" + JY_IP + ":11125/api/vms/v2/oms/diagnosis/video/plan?");
        if (name != null) {
            url.append("name=" + name + "&");
        }
        if (page_num != null) {
            url.append("page_num=" + page_num + "&");
        }
        if (page_size != null) {
            url.append("page_size=" + page_size + "&");
        }

        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url.toString(), HttpMethod.GET, httpEntity, String.class);

        return exchange.getBody();
    }

    @Override
    public String selectVideoDiagnosisPlan(String planId) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan/{plan}";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, planId);
        return exchange.getBody();
    }

    @Override
    public String deleteVideoDiagnosisPlans(String planIds) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan?ids=" + planIds;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String updatePlanStatus(String ids, Integer status) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan/status/update?ids="+ids+"&status="+status;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String getInstalledAlgos() {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.installedAlgos;
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vias/v2/awh/deployment/installed-algos?page_num=1&page_size=100";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
//        return installedAlgoStr;
    }
    @Override
    public String getVideoAnalysisTasks() {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.videoAnalysisTask;
        }
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vias/v2/video-analysis/tasks?page_num=1&page_size=100";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
//        return  videoAnalysisTaskStr;
    }

    @Override
    public String countOnlineRate(String pageSize, String pageNum) {

        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        if (pageSize == null || pageNum == null) {
            pageSize = "9999";
            pageNum = "1";
        }
        String url = "http://"+JY_IP+":11125/api/vms/v1/oms/statistics/channel/online" + "?page_size="+pageSize+"&page_num="+pageNum;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String countComplianceRatio(String pageSize, String pageNum, String queryDate) {
        //设置请求头信息
        setHeaders(headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v1/oms/statistics/channel/diagnosis";
        String params = "?page_size=" + pageSize + "&page_num=" + pageNum + "&query_date=" + queryDate;
        String realUrl = url;
        if (pageSize != null && pageNum != null && queryDate != null) {
            realUrl += params;
        }
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(realUrl, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

}
